#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void * pthread_fun1();
void * pthread_fun2();

int ticket_nums = 15; //总票数

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int main()
{
    int retn; // 创建线程返回值 若非0则创建失败
    pthread_t tid1, tid2;
    // 创建线程1
    retn = pthread_create(&tid1,NULL,pthread_fun1,NULL);
    if (retn != 0)
    {
        printf("Create error!\n");
        exit(0);
    }
    // 创建线程2
    retn = pthread_create(&tid2, NULL, pthread_fun2,NULL);
    if (retn != 0)
    {
        printf("Create error!\n");
        exit(0);
    }

    // 以下为主进程售票代码块
    while (ticket_nums >= 0)
    {
        // 票数大于0 开始售票
        pthread_mutex_lock(&lock);
        if (ticket_nums == 0)
        {
            printf("There is no ticket\n");
            pthread_mutex_unlock(&lock);
            break;
        }
        
        printf("TID:%d, Sell:%d\n", getpid(),ticket_nums);
        ticket_nums--;
        pthread_mutex_unlock(&lock);
        sleep(1); // 模拟售票需要一秒
    }

    // pthread_join函数用于等待线程退出
    retn = pthread_join(tid1, NULL);
    if (retn != 0)
    {
        printf("Join error\n");
    }
    
    retn = pthread_join(tid2, NULL);
    if (retn != 0)
    {
        printf("Join error\n");
    }
    pthread_mutex_destroy(&lock);

    return 0;
}

void * pthread_fun1()
{
    while (ticket_nums >= 0)
    {
        pthread_mutex_lock(&lock); // 上锁
        if (ticket_nums == 0)
        {
            printf("There is no ticket\n");
            pthread_mutex_unlock(&lock); // 无票 解锁
            break;
        }
        printf("TID:%u, Sell:%d\n", pthread_self(), ticket_nums);
        ticket_nums--; // 卖出一张
        pthread_mutex_unlock(&lock); // 解锁
        sleep(1);
    }
    pthread_exit("a");
}
void * pthread_fun2()
{
    while (ticket_nums >= 0)
    {
        pthread_mutex_lock(&lock);
        if (ticket_nums == 0)
        {
            printf("There is no ticket\n");
            pthread_mutex_unlock(&lock);
            break;
        }
        printf("TID:%u, Sell:%d\n", pthread_self(), ticket_nums);
        ticket_nums--;
        pthread_mutex_unlock(&lock);
        sleep(1);
    }
    pthread_exit("b");
}